package com.come4loves.core.utils;

import com.come4loves.core.comunicate.protocol.BufferFactory;
import com.come4loves.core.comunicate.protocol.ByteBufSerializer;
/**
 * 对象与通讯数组互相转换工具类
 * @author jerry
 *
 */
public class BytesUtils {
	/**
	 * 基本类型转数组
	 * @param bytes
	 * @param clz
	 * @return
	 */
	public static Object bytes2Object(byte[] bytes, final Class<?> clz) {
		ByteBufReadObject bufObject = new ByteBufReadObject(bytes, clz);
		return bufObject.getObject();
		
	}
	/**
	 * 数组转基本类型
	 * @param object
	 * @return
	 */
	public static byte[] object2Bytes(Object... object) {
		ByteBufWriteObject bufWriteObject = new ByteBufWriteObject(object);
		return bufWriteObject.getBytes();
		
	}
	
	
	
	private static class ByteBufReadObject extends ByteBufSerializer{
		public Object object;
		
		private Class<?> clz;
		public ByteBufReadObject(byte[] bytes, Class<?> clz) {
			readBuffer = BufferFactory.getIoBuffer(bytes);
			this.clz = clz;
			read();
			readBuffer.clear();
			readBuffer.release();
		}
		@Override
		protected void read() {
			object = read(clz);
		}
		
		public Object getObject() {
			
			return object;
		}
		
	}
	
	private static class ByteBufWriteObject extends ByteBufSerializer {
		private Object[] object;
		public ByteBufWriteObject(Object... object) {
			super();
			this.object = object;
		}
		
		@Override
		public void write() {
			for(Object o : object){
				this.writeObject(o);
			}
		}
		
	}
	
	public static void main(String[] args) {
		byte[] bb = BytesUtils.object2Bytes(1L);
		for (byte b : bb) {
			System.out.println(b);
		}
		Object o = BytesUtils.bytes2Object(bb, Long.class);
		System.out.println(o.getClass());
	}
}
